package com.atguigu.cloud.controller;

import com.atguigu.cloud.apis.PayFeignApi;
import com.atguigu.cloud.resp.ResultData;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
public class OrderCircuitController {
    @Resource
    private PayFeignApi payFeignApi;

    @GetMapping("/feign/pay/circuit/{id}")
    @CircuitBreaker(name = "cloud-payment-service", fallbackMethod = "myCircuitFallback")
    public String myCircuitBreaker(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuit(id);
    }

    public String myCircuitFallback(Integer id,Throwable throwable) {
        //这里是容错处理逻辑，返回备用结果
        return "myCircuitFallBack,系统繁忙, 请稍后重试...";
    }

//不该注销掉的为了演示下面的不得不注销掉,地址不变
//    @GetMapping("/feign/pay/bulkhead/{id}")
//    @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myBulkheadFallback", type = Bulkhead.Type.SEMAPHORE)
//    public String myBulkhead(@PathVariable("id") Integer id) {
//
//        return payFeignApi.myBulkhead(id);
//    }
public String myBulkheadFallback(Throwable throwable) {
    return "myBulkheadFallback,超出最大请求数量限制, 请稍后重试...";
}

    //线程池
    @GetMapping("/feign/pay/bulkhead/{id}")
    @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myBulkheadPoolFallback", type = Bulkhead.Type.THREADPOOL)
    public CompletableFuture<String> myBulkhead(@PathVariable("id") Integer id) {
        System.out.println(Thread.currentThread().getName()+"\t开始进入");
        try {
            TimeUnit.SECONDS.sleep(2);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t准备离开");
        return CompletableFuture.supplyAsync(()->payFeignApi.myBulkhead(id)+"\tBulkhead.Type.THREADPOOL");
    }
    public CompletableFuture<String> myBulkheadPoolFallback(Throwable throwable) {
        return CompletableFuture.supplyAsync(()-> "myBulkheadFallback,超出最大请求数量限制, 请稍后重试...");
    }



    @GetMapping("/feign/pay/ratelimit/{id}")
    @RateLimiter(name = "cloud-payment-service", fallbackMethod = "myRatelimitFallback")
    public String getPayById4RateLimit(@PathVariable("id") Integer id) {
        return payFeignApi.myRatelimit(id);
    }

    public String myRatelimitFallback(Throwable throwable) {
        return "超出最大请求数量限制, 请稍后重试...";
    }

//    public ResultData<String> fallback4RateLimit(Throwable throwable) {
//        return ResultData.success("服务器限流, 请稍后重试...");
//    }
}